package org.brisling.listenner.workflow;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.inf.SimpleDomainInf;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.sysman.domain.SysShortMessage;
import org.brisling.common.queryService.QueryInquiryService;
import org.brisling.sysman.service.ShortMessageService;
import org.brisling.common.util.JsonUtil;
import org.brisling.oa.queryService.QueryOABizinfoService;
import org.brisling.sysman.domain.JobRole;
import org.brisling.sysman.domain.Permissions;
import org.brisling.sysman.domain.UserRoles;
import org.brisling.sysman.domain.VOJobUser;
import org.brisling.sysman.queryService.QueryJobRoleService;
import org.brisling.sysman.queryService.QueryPermissionService;
import org.brisling.sysman.queryService.QueryUserRoleService;
import org.brisling.workflow.domain.FlowTaskConfig;
import org.brisling.workflow.queryService.QueryTaskconfigService;
import org.brisling.workflow.util.NodeUser;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * <p>
 * Title: TaskCreatedListener
 * </p>
 * <p>
 * Description: 任务节点启动监听器
 * </p>
 * <p>
 * Company: tongking
 * </p>
 * 
 * @author jackson wang
 * @since 1.0
 * @version 1.0
 * @date 2017年4月13日 下午3:58:05
 */
public class TaskCreatedListener implements ActivitiEventListener {

	// 接管人员配置项
	private static final String DEFAULT_USER_ID = "defaultUserid";

	// 人员唯一编码配置项
	private static final String USER_ID = "userid";

	// 多用户编码配置项
	private static final String USERID_IN = "userid_in";

	// 岗位角色配置项
	private static final String JOBCODE_IN = "jobcode_in";

	// 系统角色配置项
	private static final String ROLEID_IN = "roleid_in";

	// 部门配置项
	private static final String DEPTID = "deptid";
	/**
	 * 日志处理器
	 */
	private final static Log log = LogFactory.getLog(TaskCompleteListener.class);

	@Autowired
	private QueryOABizinfoService qryOaService;

	@Autowired
	private QueryInquiryService qryInquiryService;

	@Autowired
	private QueryJobRoleService jobService;

	@Autowired
	private QueryUserRoleService roleService;

	@Autowired
	private QueryTaskconfigService qryTaskconfigService;

	@Autowired
	private ShiroSecurityService shiroSecurityService;

	@Autowired
	private ShortMessageService smService;

	@Autowired
	private QueryPermissionService qryPermissionService;

	@SuppressWarnings("unchecked")
	@Override
	public void onEvent(ActivitiEvent event) {
		// TODO Auto-generated method stub
		if (event.getProcessInstanceId() != null) {

			// 短信息实体类
			SysShortMessage smd = new SysShortMessage();

			// 获取查询语句
			TaskEntity entity = (TaskEntity) ((ActivitiEntityEvent) event).getEntity();

			String flowInstId = null;

			SimpleDomainInf domain = null;

			String flowid = entity.getProcessDefinitionId();

			flowInstId = event.getProcessInstanceId();

			if (flowid != null) {
				flowid = flowid.toLowerCase();

				if (flowid.indexOf("inquiry") > 0 || flowid.indexOf("recipel") > 0) {
					domain = qryInquiryService.getOneByFlowInstId(flowInstId);
				} else {
					domain = qryOaService.getOneByFlowInstId(flowInstId);
				}

				// 增加采购类查询支持
				if (domain == null || domain.getId() == null) {
					domain = qryOaService.getPurchaseOneByFlowInstId(flowInstId);
				}
			}

			String tid = entity.getId();
			String activityName = entity.getName();
			String processDefId = entity.getProcessDefinitionId();

			Permissions p = qryPermissionService.getOneByField("flowid", processDefId);
			if (p != null && p.getShort_name() != null) {
				log.debug("------------- 获取业务名称，设置短信内容-------------");
				smd.setBizname(p.getShort_name());
				smd.setMessageContent("您新收到一条\"" + p.getShort_name() + "\"审批事项，请及时处理");
			}
			// 定义流程节点人员临时变量
			Map<String, String> flowUserMap = new HashMap<String, String>();

			if (domain == null || domain.getId() == null) {
				// 实体查询为空，业务记录尚未创建，授权给当前人员
				// event.getEngineServices()
				// .getTaskService()
				// .addCandidateUser(tid,
				// shiroSecurityService.getCurrentUserIdentify());
				String uid = shiroSecurityService.getCurrentUserIdentify();
				flowUserMap.put(uid, uid);
				log.debug("------------- 获取短信接收人信息-------------");
			} else {

				FlowTaskConfig ftc = qryTaskconfigService.getByProcDefinitionIdAndActivityName(processDefId,
						activityName);

				Map<String, Map<String, String>> _ac = null;
				if (ftc != null && ftc.getActivityConfig() != null)
					_ac = JsonUtil.bodyToObj(ftc.getActivityConfig(), HashMap.class);

				if (_ac != null) {

					Map<String, String> cMap = this.getNodeUser(_ac, domain);
					// 获取节点人员
					flowUserMap = this.getNodeUserMap(cMap);

					// 执行任务授权
					// 节点人员未配置
					if ((flowUserMap == null) || (flowUserMap.size() <= 0)) {

						String _sid = SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY);
						flowUserMap = new HashMap<String, String>();
						flowUserMap.put(_sid, _sid);
					}
					// for(String entry:uMap.keySet()){
					// if(entry!=null) {
					// event.getEngineServices()
					// .getTaskService()
					// .addCandidateUser(tid, entry);
					// }
					// }
				} else {
					// 未定义人员，分派给管理员，避免流程假死
					// event.getEngineServices()
					// .getTaskService()
					// .addCandidateUser(tid,
					// SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY));
					flowUserMap.put(ConstSysParam.SUPER_USER_IDENTIFY, ConstSysParam.SUPER_USER_IDENTIFY);
				}
			}

			// 循环设置流程节点可签收人员信息
			for (String entry : flowUserMap.keySet()) {
				log.debug("------------- 循环设置流程节点可签收人员信息 -------------");
				if (entry != null) {
					event.getEngineServices().getTaskService().addCandidateUser(tid, entry);
					smd.setUserid(entry);

					// 判断是否发送短信提醒
					log.debug("------------- 判断是否发送短信提醒 -------------");
					if (SysConfig.getConfig("sendMsg") != null) {

						// 判断是否流程启动节点
						if (domain != null && domain.getId() != null) {
							// 非启动节点，发送提醒短信
							smService.save(smd);
							// log.debug("------------- send message fired
							// -------------");
							// new Thread(){
							// @Override
							// public void run(){
							// smService.sendMsg(smd);
							// }
							// }.start();
						}

					}
				}
			}
		}

	}

	/**
	 * 获取节点用户
	 * 
	 * @return
	 */
	private Map<String, String> getNodeUser(Map<String, Map<String, String>> _ac, Object domain) {
		// 用户map
		Map<String, String> cMap = new HashMap<String, String>();

		// 角色、用户过滤
		Map<String, String> roleuserMap = null;
		// 字段定义数据
		Map<String, String> fieldMap = null;
		// 主管、分管领导过滤数据
		Map<String, String> leaderMap = null;

		if (_ac.containsKey("roleUserFilter")) {
			roleuserMap = _ac.get("roleUserFilter");
		}
		if (_ac.containsKey("fieldFilter")) {
			fieldMap = _ac.get("fieldFilter");
		}
		if (_ac.containsKey("leader")) {
			leaderMap = _ac.get("leader");
		}

		NodeUser.getInstance();
		// 获取字段条件字段值
		cMap = NodeUser.getFieldUser(fieldMap, cMap, domain);

		// 获取人员条件字段值
		cMap = NodeUser.getRoleUser(roleuserMap, cMap, domain);

		// 获取主管、分管领导过滤条件
		if (leaderMap != null && !leaderMap.isEmpty()) {

			// 获取主管领导过滤条件
			cMap = NodeUser.getLeaderUser(leaderMap, cMap, domain);
			// 业务分管领导过滤条件判断
			cMap = NodeUser.getBizLeaderUser(leaderMap, cMap, domain);

		}
		return cMap;
	}

	private Map<String, String> getNodeUserMap(Map<String, String> cMap) {

		if ((cMap == null) || cMap.isEmpty()) {
			return null;
		}
		Map<String, String> userMap = new HashMap<String, String>();

		Map<String, String> jobMap = new HashMap<String, String>();
		List<JobRole> jobrole = null;

		// 判断条件是否包含岗位角色代码
		if (cMap.containsKey(JOBCODE_IN)) {

			// 判断条件是否包含部门信息
			if (cMap.containsKey(DEPTID)) {
				Object jobcode = cMap.get(JOBCODE_IN);

				Object deptid = cMap.get(DEPTID);

				if (jobcode != null && deptid != null) {
					List<VOJobUser> lists = SysConfig.getJobUserByDept(jobcode.toString(), deptid.toString());
					if (lists != null) {
						for (VOJobUser vu : lists) {
							jobMap.put(vu.getId().toString(), vu.getId().toString());
						}
						userMap = jobMap;
					}

				}
			} else {
				jobrole = jobService.getList(cMap, false);
				if ((jobrole != null) && (jobrole.size() > 0)) {
					for (JobRole j : jobrole) {
						jobMap.put(j.getUserid(), j.getUserid());
					}
					userMap = jobMap;
				}
			}
		}

		List<UserRoles> roles = null;
		if (cMap.containsKey(ROLEID_IN)) {
			roles = roleService.getListAll(cMap);
			if ((roles != null) && (roles.size() > 0)) {
				boolean userEmpty = jobMap.isEmpty();
				Map<String, String> roleUserMap = new HashMap<String, String>();
				for (UserRoles r : roles) {
					String ruid = r.getUserid().toString();
					if (userEmpty)
						roleUserMap.put(ruid, ruid);
					else {
						if (jobMap.containsKey(ruid)) {
							roleUserMap.put(ruid, ruid);
						}
					}
				}
				userMap = roleUserMap;
			}
		}

		// 人员id条件判断
		if (cMap.containsKey("userid_in")) {
			userMap = this.splitString(cMap, userMap, "userid_in");
		}

		// 人员id条件判断
		if (cMap.containsKey(USER_ID)) {
			userMap = this.splitString(cMap, userMap, USER_ID);
		}

		// 接管人员判断
		if (userMap == null || userMap.isEmpty()) {
			// 节点人员为空，查找缺省人员设置
			userMap = this.splitString(cMap, userMap, DEFAULT_USER_ID);
		}

		return userMap;
	}

	@Override
	public boolean isFailOnException() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * 检查传入paramMap中是否存在 key 中所指定配置项，并将配置项按照逗号进行分隔，分隔后的配置项压入返回retMap中
	 * 
	 * @param paramMap 配置项map
	 * 
	 * @param retMap 返回map
	 * 
	 * @param key 待分隔的配置项 key 值
	 */
	private Map<String, String> splitString(Map<String, String> paramMap, Map<String, String> retMap, String key) {

		if (key != null && key.trim().length() > 0) {
			return null;
		}
		if (paramMap.containsKey(key)) {
			String _uid = paramMap.get(key);
			if (_uid != null && _uid.trim().length() > 0) {
				String[] uarray = _uid.split(",");
				if (uarray.length >= 0) {
					// 判断返回参数是否为空
					if (retMap == null) {
						retMap = new HashMap<String, String>();
					}
					for (String _id : uarray) {
						if (_id != null && _id.trim().length() > 0) {
							retMap.put(_id, _id);
						}
					}
				}
			}
		}

		return retMap;
	}

}
